﻿// Author: Marcel Medina
// Website: http://www.sharepoint4developers.net
// Source Code available at Codeplex

// Load script
ExecuteOrDelayUntilScriptLoaded(function () { }, "sp.js");

var line = '';

// Function that does the trick
// by getting the Document Url and
// copying to the Clipboard
function copyLinkToClipboard(url) {

    // Get the correct path
    url = url.replace(parseUrl(url), '');
    var copyUrl = url;
    var count = 0;

    // Get the Document Url
    $('tr .s4-itm-selected').each(function () {
        var control = $(this).find('.ms-vb-title a');

        var href = control.attr('href');
        copyUrl += replaceEmpty(control.attr('href'), '%20');
        line = line.concat(control.text(), ' - ', copyUrl, '\n');

        copyUrl = url;
        count++;
    });

    // Copy to Clipboard
    if (window.clipboardData) {
        window.clipboardData.setData('text', '');
        window.clipboardData.setData('text', line);

        var msg = 'Copied to Clipboard';
        if (line != '' && window.clipboardData.getData('text') == line) {
            if ($('#notificationArea SPAN.s4-noti-in3').text() != msg) {
                SP.UI.Notify.addNotification(msg, false);
            }
        }
        
        line = '';
    }
}

// Function that parses the Url
// and gets the third match (path)
function parseUrl(data) {
    var e = /^(http:\/\/)?([^:\/\s]+)((\/\w+)*(\/)?)$/;

    return (data.match(e)) ? RegExp.$3 : "";
}

// Function that replaces spaces
// with the value provided
function replaceEmpty(data, value) {
    var letters = [];

    for (var i = 0; i < data.length; i++) {
        letters[i] = data.charAt(i).replace(' ', value);
    }

    return letters.join("");
}

// Function that enables the Ribbon button
// by checking whether the field LinkFilename
// is available in the view
function enableCopyLinkToClipboard() {
    var contain = false;
    var items = SP.ListOperation.Selection.getSelectedItems();

    $('div.ms-vh-div').each(function () {
        var view = $(this).attr('sortfields').split('&')[1].split('=')[1];
        if (view == 'LinkFilename') {
            contain = true;
        }
    });

    return (items.length > 0 && contain);
}